<?php
namespace app\index\controller;

use think\Db;
use think\facade\Cache;
use think\Controller;

class Index extends Controller
{
    # /authorize?response_type=code&client_id=testclient&state=xyz
    public function authorize()
    {
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
 
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
 
 
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();
    
        // validate the authorize request
        if (!$server->validateAuthorizeRequest($request, $response)) {
            // dump($server);
            dump('111');
            die;
        }
        // display an authorization form
        if (empty($_POST)) {
          exit('
        <form method="post">
          <label>Do You Authorize TestClient username is '.$_GET['client_id'].'?</label><br />
          <input type="submit" name="authorized" value="yes">
          <input type="submit" name="authorized" value="no">
        </form>');
        }
 
        // print the authorization code if the user has authorized your client
        $is_authorized = ($_POST['authorized'] === 'yes');
        $server->handleAuthorizeRequest($request, $response, $is_authorized);
        if ($is_authorized) {
          // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
          $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
          exit("SUCCESS! Authorization Code: $code");
        }
        $response->send();
    }

    public function authorize222(){
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();

        $server->handleAuthorizeRequest($request, $response, true);

        // parse the returned URL to get the authorization code
        $parts = parse_url($response->getHttpHeader('Location'));
        parse_str($parts['query'], $query);

        // pull the code from storage and verify an "id_token" was added
        $code = $server->getStorage('authorization_code')
                ->getAuthorizationCode($query['code']);
        // var_export($code);
        echo json_encode($code);
    }

    public function implicit(){
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage, array('allow_implicit' => true));

        $request = \OAuth2\Request::createFromGlobals();
        $response = new \OAuth2\Response();

        // validate the authorize request
        if (!$server->validateAuthorizeRequest($request, $response)) {
            dump('111');
        }
        // display an authorization form
        if (empty($_POST)) {
          exit('
        <form method="post">
          <label>Do You Authorize TestClient username is '.$_GET['client_id'].'?</label><br />
          <input type="submit" name="authorized" value="yes">
          <input type="submit" name="authorized" value="no">
        </form>');
        }
 
        // print the authorization code if the user has authorized your client
        $is_authorized = ($_POST['authorized'] === 'yes');
        $server->handleAuthorizeRequest($request, $response, $is_authorized);
        if ($is_authorized) {
          // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client
          $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40);
          exit("SUCCESS! Authorization Code: $code");
        }
        $response->send();
    }

    public function token(){
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
        // dump($server);die;
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
 
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));

        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        $server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();

    }

    public function pass(){
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
        
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
 
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
 
        $server->addGrantType(new \OAuth2\GrantType\UserCredentials($storage));

        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        $server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

    public function refresh_token(){
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
 
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));

        $server->addGrantType(new \OAuth2\GrantType\RefreshToken($storage,array(
            "always_issue_new_refresh_token" => true,   //Issue a new refresh token
            "unset_refresh_token_after_use" => true,
            "refresh_token_lifetime" => 2419200,
            )
        ));
 
        // Handle a request for an OAuth2.0 Access Token and send the response to the client
        $server->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

    public function resource(){
        // include our OAuth2 Server object
        global $server;
        $dsn      = 'mysql:dbname=www_token_com;host=mysql';
        $username = 'root';
        $password = 'root';
 
        \OAuth2\Autoloader::register();
 
        // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));
 
        // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);
 
        // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));
 
        // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));
 
 
        // Handle a request to a resource and authenticate the access token
        if (!$server->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            $server->getResponse()->send();
            die;
        }
        echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
    }

}
